package com.example.tms.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.tms.common.annotation.LogAction;
import com.example.tms.common.enums.Result;
import com.example.tms.entity.Department;
import com.example.tms.service.DepartmentService;

@RestController
@RequestMapping("/departments")
public class DepartmentController {
    private static final org.apache.logging.log4j.Logger log =
            org.apache.logging.log4j.LogManager.getLogger(EmployeeController.class);

    @Autowired
    private DepartmentService departmentService;

    // GET 请求：获取所有部门
    @LogAction("查询所有部门")
    @GetMapping("")
    @PreAuthorize("hasAnyRole('ADMIN','HR','EXECUTIVE')")
    public Result selectAll(Department department) {
        List<Department> list = departmentService.selectAll();
        return Result.success(list);
    }
    
    // GET: 根据 ID 获取部门
    @LogAction("根据id查询部门")
    @GetMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public Result selectById(@PathVariable Integer id) {
        Department department = departmentService.selectById(id);
        return Result.success(department);
    }

    // POST: 添加部门
    @LogAction("添加部门")
    @PostMapping("")
    @PreAuthorize("hasRole('ADMIN')")
    public Result add(@RequestBody Department department) {
        int result = departmentService.insert(department);
        return result > 0 ? Result.success() : Result.error("添加失败");
    }

    // PUT: 更新部门信息
    @LogAction("更新部门")
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result update(@PathVariable Integer id, @RequestBody Department department) {
        department.setId(id); // 将路径参数的 id 设置到 department 对象中
        int result = departmentService.update(department);
        return result > 0 ? Result.success() : Result.error("更新失败");
    }

    // DELETE: 删除部门
    @LogAction(value = "删除部门",level = "WARN")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result delete(@PathVariable Integer id) {
        int result = departmentService.deleteById(id);
        return result > 0 ? Result.success() : Result.error("删除失败");
    }
}
